<?php

namespace app\admin\business;

use app\common\business\BusiBase;
use think\Exception;
use think\facade\Request;
use app\common\model\mysql\AdminUser as AdminUserModel;

/**
 * 后台用户表
 */
class AdminUser extends BusiBase
{
    public function __construct()
    {
        $this->model = new AdminUserModel();
    }

    public function getAdminUserByUsername($username)
    {
        $userInfo  = $this->model->getAdminUserByUsername($username);
        // 判断用户是否存在且状态正常
        if (empty($userInfo) || $userInfo['status'] != config('status.mysql.table_normal')) return false;
        $userData = $userInfo->toArray();
        return $userData;
    }

    /**
     * 后台用户登录部分
     *
     * @param $data
     * @return \think\response\Json
     */
    public function login($data)
    {
        try{
            // 获取用户信息
            $userData  = $this->getAdminUserByUsername($data['username']);
            if (!$userData) throw new Exception('当前用户不存在!');

            // 判断用户密码是否正确
            if ($userData['password'] != md5($data['password'].$userData['passsalt'])) {
                throw new Exception("密码错误");
            }

            // 更新当前用户数据
            $updateData = [
                'last_login_time' => time(),
                'last_login_ip'   => Request::ip()
            ];
            $res   = $this->edit(intval($userData['id']), $updateData);
            if (!$res) return show(config('status.error'), '登陆失败');
        } catch (\Exception $e) {
            // todo 记录日志 $e->getMessage();
            throw new Exception($e->getMessage());
        }
        //  session 记录当前数据
        session(config('admin.session_admin'), $userData);
        return true;
    }
}